package com.kangjia.config;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

@Configuration
public class RedisConfig {

	@Value("${redis.maxIdle}")
	private int maxIdle;
	@Value("${redis.maxTotal}")
	private int maxTotal;
	@Value("${redis.masterName}")
	private String masterName;
	@Value("${redis.host}")
	private String host;
	@Value("${redis.credit}")
	private String credit;
	@Value("${redis.sentinel.host}")
	private String sentinel;

	@Bean
	public JedisPoolConfig jedisPoolConfig() {
		JedisPoolConfig jpc = new JedisPoolConfig();
		jpc.setMaxIdle(maxIdle);
		jpc.setMaxTotal(maxTotal);
		jpc.setTestOnBorrow(true);
		return jpc;
	}

	@Bean
	public JedisSentinelPool jedisSentinelPool(JedisPoolConfig jpc) {
		if (StringUtils.isNotBlank(sentinel)) {
			String[] hosts = sentinel.split(",");
			Set<String> sets = new HashSet<>();
			for (String host : hosts) {
				sets.add(host);
			}
			JedisSentinelPool jsp = new JedisSentinelPool(masterName, sets, jpc);
			return jsp;
		}
		return null;
	}

	@Bean
	public JedisPool jedisPool(JedisPoolConfig jpc) {
		String[] hosts = host.split(":");
		JedisPool pool = new JedisPool(jpc, hosts[0], Integer.parseInt(hosts[1]), 10000, StringUtils.isNoneBlank(credit) ? credit : null);
		return pool;
	}
}